
#pragma once

#include <stdint.h>
#include "RP6I2CmasterTWI.h"

#define I2C_DATAID_CMPS03_DIR		5

#define MAKE_CMPS03(CMPS, ADDRESS)  CMPS=createCMPS03(ADDRESS)

typedef struct cmps03_str cmps03_t;

struct cmps03_str{
	uint8_t address;
	uint8_t initialized;
	uint8_t(*checkData)(uint8_t dataRequestId, cmps03_t *cmps);
	uint8_t (*measure)(cmps03_t *cmps);
	uint8_t isMeasuring;
	uint16_t direction;
};



uint8_t CMPS03_checkI2CDataReady(uint8_t dataRequestId,cmps03_t *cmps){
	uint8_t messageBuf[2]={0};
	switch(dataRequestId)
	{
		case I2C_DATAID_CMPS03_DIR:
		//TODO: Auf ein Byte umstellen
		{
			I2CTWI_getReceivedData(messageBuf, 2);
			cmps->direction = messageBuf[1] + (messageBuf[0] << 8);
			cmps->isMeasuring=false;
			return true;
		}
	}
	return false;
}

void CMPS03_measure(cmps03_t *cmps){
	if(!cmps->isMeasuring)
	{
		if(TWI_operation == I2CTWI_NO_OPERATION)
		{
			I2CTWI_requestRegisterFromDevice(cmps->address, I2C_DATAID_CMPS03_DIR, 2,2);
			cmps->isMeasuring = true;
		}
	}
}

void initializeCMPS03(cmps03_t *cmps, uint8_t addressP){
	cmps->initialized=true;
	cmps->address=addressP;
	cmps->isMeasuring=false;
	cmps->checkData=&CMPS03_checkI2CDataReady;
	cmps->measure=&CMPS03_measure;
}


cmps03_t *createCMPS03(uint8_t addressP){
	cmps03_t *ret=(cmps03_t*)malloc(sizeof(cmps03_t));
	initializeCMPS03(ret, addressP);
	return ret;
}

